// this 就是 ctx 对象，在其中可以调用 ctx 上的其他方法，或访问属性

const jwt = require('jsonwebtoken');
const tokenKey = 'C*F-JaNdRgUkXn2r5u8x/A?D(G+KbPeShVmYq3s6v9y$B&E)H@McQfTjWnZr4u7w777-COURSEAPI';
const Constant = require('../config/Constant');
const libqqwry = require('lib-qqwry');
const moment = require('moment');

module.exports = {

    getIP() {
        return this.request.headers['x-real-ip'] || this.request.headers['x-forwarded-for'] || this.request.ip;//this.request.ip;
    },

    getIpLocal() {
        try {
            let qqwry = libqqwry.init();
            qqwry.speed(); //若初始化时没有启用急速模式,可以这样启用;
            let ip1 = qqwry.searchIP(this.request.headers['x-real-ip'] || this.request.headers['x-forwarded-for'] || this.request.ip); //查询IP信息
            if (ip1) {
                let c = ip1.Country;
                if(c === '局域网'){
                    c = '未知'
                }
                return c;
            } else {
                return '';
            }
        } catch (e) {
            return '';
        }
    },


    createToken({login_user_key, email, name, id}) {
        let token = jwt.sign({
            exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 30),
            data: {
                id: id,
                login_user_key: login_user_key,
                email: email,
                name: name,
                ts: new Date().getTime()
            }
        }, tokenKey);
        return {token: Constant.TOKEN_PREFIX + token};
    },


    verifyToken(token) {
        return new Promise(function (resolve, reject) {
            let arr1 = token.split(' ');
            if (arr1[1]) {
                token = arr1[1]
            }
            jwt.verify(token, tokenKey, function (err, decoded) {
                if (err || !decoded) {
                    resolve(null);
                } else {
                    resolve(decoded.data)
                }
            });
        });
    },


    getUserName(tokenUserInfo) {
        let e = '';
        if (tokenUserInfo) {
            if (tokenUserInfo.name) {
                e = tokenUserInfo.name;
            } else if (tokenUserInfo.email) {
                e = tokenUserInfo.email;
            }
        }
        return e;
    },



    formatDate(date, format) {
        /*  if (!date) {
              date = new Date();
          }
          if (!format) {
              format = 'YYYY-MM-DD HH:mm:ss';
          }
          return moment(date).format(format);*/
        return date;
    },



    formatDateV2(date, format) {
          if (!date) {
              date = new Date();
          }
          if (!format) {
              format = 'YYYY-MM-DD HH:mm:ss';
          }
          return moment(date).format(format);
        return date;
    },

    getLoginInfo() {
        let tokenUserInfo = this.request.body?this.request.body.tokenUserInfo:null;
        tokenUserInfo =  {}
        if (tokenUserInfo) {
            return {
                operatorType: tokenUserInfo.type,
                operatorId: tokenUserInfo.userId||'123',
                createBy: this.getUserName(tokenUserInfo),
                isAdmin: tokenUserInfo.admin,
                operatorShopId:tokenUserInfo.shopId,
                userNo:tokenUserInfo.userNo
            }
        } else {
            return {};

        }
    },




    isObject(val) {
        return Object.prototype.toString.call(val) === '[object Object]';
    },

    async refreshToken(key) {
        let redUser = await this.service.redis.get(Constant.LOGIN_TOKEN_KEY + key);
        let lastRefreshTime = redUser.lastRefreshTime;
        if (redUser) {
            if (!lastRefreshTime || Math.abs(lastRefreshTime - new Date().getTime()) >= 60 * 10 * 1000) {
                console.info('refreshToken');
                redUser.expireTime = new Date(moment().add(Constant.appExpireTime, 'minutes')).getTime();//过期时间
                redUser.lastRefreshTime = new Date().getTime();//最新刷新token时间
                await this.service.redis.set(Constant.LOGIN_TOKEN_KEY + key, JSON.stringify(redUser), Constant.appExpireTime * 60);
            }
        }
        return null;
    },

    async getUserNo(){
        let result = await this.service.sysUid.getUserNo();
        return result;
    },

    async genShopNo(){
        let result = await this.service.sysUid.getShopNo();
        return result;
    },

    async genGoodsNo(){
        let result = await this.service.sysUid.getGoodsNo();
        return result;
    },

    positiveInteger(value){
        if(value === ''){
            return false;
        }
        if(!isNaN(parseFloat(value)) && isFinite(value)){
            if(Number(value) < 0){
                return false;
            }
        }
        if(Object.prototype.toString.call(Number(value)) === '[object Number]' && Number(value)>=0){
            return true;
        }else{
            return false;
        }
    },


    async PUBLISH_GOODS(){
        let result = await this.service.sys.querySysParam('PUBLISH_GOODS');
        return Number(result);
    },


    async TRADE_RATE(){
        let result = await this.service.sys.querySysParam('TRADE_RATE');
        return Number(result);
    },


    MARGIN_MAP(key){
        const obj = {
            wechat: '微信',
            alipay: '支付宝',
            balance: '余额',
            margin: '预存保证金'
        };
        return obj[key];
    },

    checkNicknameLengthValid(str){
        //昵称最多16个字节
        let byteLength = 0;
        for (let i = 0; i < str.length; i++) {
            let charCode = str.charCodeAt(i);
            if (charCode <= 0x007f) {
                byteLength += 1;
            } else if (charCode <= 0x07ff) {
                byteLength += 2;
            } else {
                byteLength += 2;
            }
        }
        return byteLength>0 && byteLength<=16;
    },

    extractNumbers(str){
        if(!str){
            return [0];
        }
        str = str +'';
        // 正则表达式匹配所有的数字，包括整数和小数
        const regex = /\d+(\.\d+)?/g;
        // 使用match方法获取所有匹配的结果
        const matches = str.match(regex);
        // 返回包含数字的数组，如果没有匹配则返回null
        return matches ? matches.map(Number) : [];
    }
};
